import numpy as np
import torch


def dem00():
    x1 = torch.ones(3, 3)
    print(f"x1:{x1}")
    x = torch.ones(2, 2, requires_grad=True)
    print(f"x2:{x}")

    # 执行加法运算
    y = x + 2
    print(f"y:{y}")
    # 执行乘法运算
    z = x * 3
    print(f"z:{z}")

    print(f"y.grad_fn:{y.grad_fn}")
    print(f"x.grad_fn:{x.grad_fn}")
    print(f"z.grad_fn:{z.grad_fn}")


def dem01():
    x1 = torch.ones(3, 3)

    x = torch.ones(2, 2, requires_grad=True)

    y = x + 2
    z = y * y * 3
    out = z.mean()
    print(f"z:{z}")
    print(f"out:{out}")


def dem02():
    a = torch.tensor([[1, 2], [3, 4]])
    print(f"a:{a}")
    a = ((a * 3) / (a - 1))
    print(a.requires_grad)  # False
    a.requires_grad_(True)
    print(a.requires_grad)
    b = (a * a).sum()
    print(b.grad_fn)
    print(b)
    b.backward()
    print(a.grad)


if __name__ == '__main__':
    # dem00()
    # dem01()
    dem02()
